var tbar = Ext.create('Ext.toolbar.Toolbar', {
	dock : 'top',
	layout: {  
        overflowHandler: 'Menu'  
    },  
	items : [{
		id:'userName',
		xtype : 'textfield',
		name : 'userName',
		fieldLabel : '用户名',
		labelWidth : 50,
		width : 195,
		emptyText : '===请填写用户名===',
		listeners:{
			'blur':function(){
				search();
			}
		}
	},{
		id:'nickName',
		xtype : 'textfield',
		name : 'nickName',
		fieldLabel : '姓名',
		labelWidth : 30,
		width : 160,
		emptyText : '===请填写姓名===',
		listeners:{
			'blur':function(){
				search();
			}
		}
	},{
		text : '查询',
		handler : function() {
			search();
		}
	},{
		text : '重置',
		handler : function() {
			Ext.getCmp("userName").setValue("");
			Ext.getCmp("nickName").setValue("");
			search();
		}
	},{
		xtype : 'button',
		text : '添加',
		id : 'add'
	}, {
		/*xtype : 'button',
		text : '删除',
		id : 'delete'
	}, {*/
		xtype : 'button',
		text : '保存',
		id : 'save'
	}]
});

function search(){
	var userName = Ext.getCmp("userName").getValue();
	var nickName = Ext.getCmp("nickName").getValue();
	
	// 获取grid的store
	var adminStore = Ext.getCmp("admingrid").getStore();
	adminStore.load({
		params : {
			userName : userName,
			nickName : encodeURIComponent(nickName)
        }
	});
}

Ext.define("app.view.AdminGrid", {
			extend : "Ext.grid.Panel",
			xtype: 'cell-editing',
			alias : "widget.admingrid",
			id : "admingrid",
			width:700,
			height:350,
			viewConfig:{
		         loadMask:false  // grid去掉加载中的提示
		    },
			selModel : {
				//selType : "checkboxmodel"
			},
			border : 0,
			multiSelect : true,
			frame : false, // 不要边框
			tbar : tbar,
			bbar : {
				xtype : 'pagingtoolbar',
				store : 'AdminStore',
				dock : 'bottom',
				displayInfo : true
			},
			viewConfig:{  
		        enableTextSelection:true  // 文本可选择
		    },
			enableKeyNav : true,
			columnLines : true,
			forceFit :true, // 宽度自适配
			columns : [{
						text:"序号",
						dataIndex:"id",
						width:20
					},{
						text : "用户名",
						dataIndex : "userName",
						width : 80,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "姓名",
						dataIndex : "nickName",
						width : 80,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "密码",
						dataIndex : "userPwd",
						width : 80,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "用户类型",
						dataIndex : "userType",
						width : 60,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			            //    disabled:true,
			                store : [
	                         ['1', '超级管理员'],
			                 ['2', '普通管理员'],
			                 ['3', '运营'],
			                 ['4', '开发'],
			                 ['5', '测试']]
			            },
			            renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if (v==1) {
					        	v = "<font style='color:red'>超级管理员</font>";
					        }else  if (v==2) {
					        	v = "<font>普通管理员</font>";
					        }else  if (v==3) {
					        	v = "<font>运营</font>";
					        }else  if (v==4) {
					        	v = "<font>开发</font>";
					        }else  if (v==5) {
					        	v = "<font>测试</font>";
					        }
					        return v;
					    }
					},{
							text : "用户状态",
							dataIndex : "statue",
							width : 60,
							editor : {
				                xtype : 'combobox',
				                editable : false,
				            //    disabled:true,
				                store : [['0', '正常'],
		                         ['1', '删除']
//				                ,
//				                 ['2', '冻结']
				                ]
				            },
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if (v==1) {
					        	v = "<font style='color:red'>删除</font>";
					        }else  if (v==2) {
					        	v = "<font style='color:gray'>冻结</font>";
					        }else{
					        	v = "正常";
					        }
					        return v;
					    }
					},{
		                xtype: 'actioncolumn',
		                width: 17,
		                tdCls: 'action',  
		                text: '操作',  
		                sortable: false,
		                menuDisabled: true,
		                items: [{
		                    icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/add.png',
		                    tooltip: '权限配置',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                    	var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        var statue = record.get('statue');
		                        this.authUserById(grid,id,statue);
		                    },
		                    getClass: function(v, meta, record) {
		                    	var userType = record.get('userType');
		                    	var dataIndex = record.get('id');
		                        if (userType == '1' || userType == '3' || userType == '4' || userType == '5' || dataIndex == '0') {
		                              return 'emptyCss';
		                        }else{
		                              return '';
		                        }
		                    }
		                }
//		                ,{
//		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/special.png',
//		                    tooltip: '冻结',
//		                    scope: this,
//		                    handler: function(grid, rowIndex, colIndex) {
//		                        var record = grid.getStore().getAt(rowIndex);
//		                        var id = record.get('id');
//		                        var statue = record.get('statue');
//		                        this.lockUserById(grid,id,statue);
//		                    },
//		                    getClass: function(v, meta, record) {
//		                    	var userType = record.get('userType');
//		                    	var dataIndex = record.get('id');
//		                        if (userType == '1' || userType == '3' || userType == '4' || userType == '5' || dataIndex == '0') {
//		                              return 'emptyCss';
//		                        }else{
//		                              return '';
//		                        }
//		                    }
//		                }
		                ,{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/close.png',
		                    tooltip: '删除',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                        var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        var statue = record.get('statue');
		                        this.deleteUserById(grid,id,statue);
		                    },
		                    getClass: function(v, meta, record) {
		                    	var userType = record.get('userType');
		                    	var id = record.get('id');
		                        if (userType == '1' || userType == '3' || userType == '4' || userType == '5' || id == '0') {
		                              return 'emptyCss';
		                        }else{
		                              return '';
		                        }
		                    }
		                }]
		            }],
			listeners: { 
				beforeedit: function (editor, e, eOpts) {
		            if(e.field == 'createTime'){
		            	return false;
		            }else if(e.record.raw.username == 'admin' && (e.field == 'userType' || e.field == 'username')){
		            	return false;
		            }else{
		            	return true;
		            }
		        }
			},					
			initComponent : function() {
				// 可编辑插件
				this.editing = Ext.create("Ext.grid.plugin.CellEditing");
				this.plugins = [this.editing];
				this.callParent(arguments);
			},
			store : "AdminStore"
});

// 根据id删除用户
function deleteUserById(grid,id,statue){
	if(statue != 0){
		Ext.example.msg('', '不允许删除', '');
	}else{
		var store = grid.getStore();
		Ext.Ajax.request({
			url : "deleteBatchAdmin",
			params : {
				ids : id,
				sing : false
			},
			type : "POST",
			timeout : 4000,
			success : function(response, opts) {
				var result = eval('('+response.responseText+')');
				if(result.resultCode == 'success'){
					// 刷新grid
					store.load();
					Ext.example.msg('', '删除成功', '');
				}else{
					Ext.example.msg('', '删除失败', '');
				}
			}
		});
	}
}

//根据id锁定用户
function lockUserById(grid,id,statue){
	if(statue != 0){
		Ext.example.msg('', '不允许冻结', '');
	}else{
		var store = grid.getStore();
		Ext.Ajax.request({
			url : "lockBatchAdmin",
			params : {
				id : id
			},
			type : "POST",
			timeout : 4000,
			success : function(response, opts) {
				var result = eval('('+response.responseText+')');
				if(result.resultCode == 'success'){
					// 刷新grid
					store.load();
					Ext.example.msg('', '冻结成功', '');
				}else{
					Ext.example.msg('', '冻结失败', '');
				}
			}
		});
	}
}


//根据id给用户配置权限
function authUserById(grid,id,statue){
	if(statue != 0){
		Ext.example.msg('', '不允许配置', '');
	}else{
		var store = grid.getStore();
		// 权限树
		Ext.define('app.view.authTree', {
		    extend: 'Ext.tree.Panel',
		    requires: [
		        'Ext.data.TreeStore'
		    ],
		    xtype: 'check-tree',
		    rootVisible: false,
		    useArrows: true,
		    
		    initComponent: function(){
		        Ext.apply(this, {
		            store: new Ext.data.TreeStore({
		                proxy: {
		                    type: 'ajax',
		                    url: 'getAdminAuthTree?adminId='+id
		                }/*,
		                sorters: [{
		                    property: 'leaf',
		                    direction: 'ASC'
		                }, {
		                    property: 'text',
		                    direction: 'ASC'
		                }]*/
		            })
		        });
		        this.callParent();
		    }
		});
		
		var authTreeFrom = Ext.create('app.view.authTree', {
	        layout: 'absolute',
	        url: 'save-form.php',
	        defaultType: 'textfield',
	        border: false,
	        layout: 'fit'
	    });
		
	    var win = Ext.create('Ext.window.Window', {
	    	autoShow: true,
	        title: '权限树',
	        width: 400,
	        height: 500,
	        minWidth: 300,
	        minHeight: 200,
	        layout: 'fit',
	        plain:true,
	        modal: 'true',  // 模态
	        collapsible: true, //允许缩放条  
	        closeAction: 'destroy',    
	        closable: true, 
	        maximizable :true,
	        items: authTreeFrom,
	        buttonAlign: "center",  
	        buttons: [{
	            text: '保存',
	            handler: function() {
	            	// 获取选中的游戏Id
	            	var records = authTreeFrom.getView().getChecked();
	            	gameIds = [];
	                Ext.Array.each(records, function(rec){
	                	gameIds.push(rec.raw.functionId);
	                });
	                
	                // 更新权限
	                Ext.Ajax.request({
						url : "updateAdminAuth",
						params : {
							ids : "" + gameIds.join(",") + "",
							adminId : "" + id
						},
						type : "POST",
						timeout : 4000,
						success : function(response, opts) {
							var result = eval('('+response.responseText+')');
							if(result.resultCode == 'success'){
								// 关闭窗口
				            	win.close();
								// 刷新grid
								store.load();
								Ext.example.msg('', '保存成功', '');
							}else{
								Ext.example.msg('', '保存失败', '');
							}
						}
	                });
	            }
	        },{
	            text: '取消',
	            handler: function() {
	            	// 关闭窗口
	            	win.close();
	            }
	        }]
	    });
	}
}